package com.uptang.paper.util;

import fmath.conversion.ConvertFromMathMLToLatex;
import fmath.conversion.ConvertFromWordToMathML;
import lombok.extern.slf4j.Slf4j;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class MathMLToLatexUtil {

    /**
     * 案例参数:
     * String test = "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"><msup><mi>n</mi><mrow><mi>p</mi><mo>-</mo><mn>1</mn></mrow></msup><mspace width=\".2em\"/><mo>≡</mo><mspace width=\".2em\"/><mn>1</mn><mspace width=\".2em\"/><mo>(</mo><mi>mod</mi><mspace width=\".2em\"/><mi>p</mi><mo>)</mo></math>";
     *
     * @param strText 参数
     * @return Latex
     */
    public static String tMathMLToLatex(String strText) {
        String keys = "<math.*?</math>";
        Pattern pattern = Pattern.compile(keys);
        String strResult = "";

        try {
            Matcher matcher = pattern.matcher(strText);
            StringBuffer sbr = new StringBuffer();
            while (matcher.find()) {
                String strTmp = matcher.group();
                try {
                    strTmp = strTmp.replace("<math xmlns=\'http://www.w3.org/1998/Math/MathML\'>", "<math>");
                    strTmp = strTmp.replaceAll("<math[^>]*>", "<math>");
                    strTmp = ConvertFromMathMLToLatex.convertToLatex(strTmp);
                    strTmp = strTmp.replace("\\", "##");
                    strTmp = "@@" + strTmp + "@@";
                } catch (Exception e) {
                    // TODO: handle exception
                    strTmp = "";
                    e.printStackTrace();
                }

                matcher.appendReplacement(sbr, strTmp);
            }
            matcher.appendTail(sbr);
            strResult = sbr.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        strResult = strResult.replace("@@", "$");
        strResult = strResult.replace("##", "\\");

        log.info("latex:{}", strResult);
        return strResult;
    }

    public static void main(String[] args) {
        String mathMLFromDocStream = ConvertFromWordToMathML.getMathMLFromDocFile("D:\\test1.docx");
        String stringNoBlank = getStringNoBlank(mathMLFromDocStream);
        String s = tMathMLToLatex(stringNoBlank);
        System.out.println(s);
    }


    public static String getStringNoBlank(String str) {
        if (str != null && !"".equals(str)) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            String strNoBlank = m.replaceAll("");
            return strNoBlank;
        } else {
            return str;
        }
    }

}